/**
 * 按钮
 */
class ButtonEx extends eui.Button {

    id: any;
    tween: boolean = true;

    public constructor(tween = true) {
        super();
        this.tween = tween;
    }

    childrenCreated() {
        super.childrenCreated();

        this.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.clickHandler, this);
        this.addEventListener(egret.TouchEvent.TOUCH_END, this.clickHandler, this);
        this.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE, this.clickHandler, this);
    }

    private clickHandler(e: egret.TouchEvent): void {

        if (!this.tween) return;

        let img: eui.Image = <eui.Image>this.getChildAt(0);
        if (img) {
            img.verticalCenter = img.horizontalCenter = 0;

            switch (e.type) {
                case egret.TouchEvent.TOUCH_BEGIN:
                    img.percentWidth = img.percentHeight = 95;
                    break;
                case egret.TouchEvent.TOUCH_END:
                case egret.TouchEvent.TOUCH_RELEASE_OUTSIDE:
                    img.percentWidth = img.percentHeight = 100;
                    break;
            }
        }
    }

    set source(res: any) {
        let img: eui.Image = <eui.Image>this.getChildAt(0);
        if (img) {
            img.source = res;
        }
    }

    static initPos(button: any) {
        button.initx = button.x;
        button.inity = button.y;
        button.anchorOffsetX = button.width / 2;
        button.anchorOffsetY = button.height / 2;
        button.x = button.initx + button.anchorOffsetX;
        button.y = button.inity + button.anchorOffsetY;
    }

    static draw(button: any) {
        ButtonEx.initPos(button);
    }

    public initEvent(button: any) {
        button.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.clickHandler, this);
        button.addEventListener(egret.TouchEvent.TOUCH_END, this.clickHandler, this);
        button.addEventListener(egret.TouchEvent.TOUCH_RELEASE_OUTSIDE, this.clickHandler, this);
    }
}